package com.moon.game.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Properties;

public class ConfigUtil
{
	public static InputStream loadFile(String resource,Class clazz)
	{
	  	ClassLoader classLoader =  null;
	    try 
	    {
	    	Method method = Thread.class.getMethod("getContextClassLoader");
	    	classLoader =  (ClassLoader) method.invoke(Thread.currentThread());
	    }
	    catch (Exception e) 
	    {
	    }
		if(classLoader == null)
		{
			classLoader = clazz.getClassLoader(); 	
		}
		try 
		{
			if (classLoader != null) 
			{
				URL url = classLoader.getResource(resource);
				if(url == null)
				{
					System.out.println("Can not find resource:"+ resource);
					return null;
				}
				if(url.toString().startsWith("jar:file:"))
				{
					return clazz.getResourceAsStream(resource.startsWith("/") ? resource : "/"+ resource);
				}
				else
				{
					return new FileInputStream(new File(url.toURI()));
				}
			}			
		}
		catch(Exception e) 
		{
		}
		return null;
	}
	
    public static Properties loadProperties(String fileName) {
        Properties properties = new Properties();

        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(fileName);
            properties.load(inputStream);
        }catch(Exception e){
        } finally {
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
        }
        return properties;
    }
}
